$(function(){
	var detailId=queryString('updateId');
	var flowId=queryString('flowid');
		var checkFlag={sele:false,pes:false,sort:false};
	requestDetail(detailId);
	requestClassification();
	requestPort();		
	requestSort();
	requestSource();
	var file={};
	//任务派遣
	$("#Dispatch").click(function(){
		getInformation();
	})
	$("#finishInfo").click(function(){
		finishInfo();
	})
	
	
	$(document).on('click','.glyphicon-remove',function(){
		$(this).parent().remove();
	});
			
	
	
	

//向后台请求分级信息
function requestClassification()
{	
	var url="getAllInformationClassification.do";//分级地址
	var data={};
	var object={};
	data=YuXi.util.get(url,"null",function(data){
		object=data.object;
		//用data循环添加分口信息
		for(var i=0;i<object.length;i++)
		{
			var html="<option  value="+object[i].id+" >"+object[i].name+"</option>";
			$(".pes").append(html);
		}
		checkFlag.pes=true;
	},function(){
		
	});//请求数据
	
}

//向后台请求分口信息
function requestPort()
{	var url="getAllInformationPort.do";//分口地址
	var data={};
	var object={};
	data=YuXi.util.get(url,null,function(data){
		object=data.object;
		//用data循环添加分口信息	
		for(var i=0;i<object.length;i++)
		{
			 var html="<option  value="+object[i].id+" >"+object[i].portName+"</option>";
			 $(".sele").append(html);
		}
		checkFlag.sele=true;
	},function(){});//请求数据
	
}

//向后台请求分类信息
function requestSort()
{	//数据模拟

	
	
	var url="getAllInfomationSort.do";//分类地址
	var data={};
	var object={};
	data=YuXi.util.get(url,"null",function(data){
		object=data.object;
		//用data循环添加分类信息
		for(var i=0;i<object.length;i++)
		{
			var html="<option  value="+object[i].id+" >"+object[i].name+"</option>";
			$(".sort").append(html);
		}
		checkFlag.sort=true;
	},function(){
		
	});//请求数据
	
}

//向后台请求渠道信息
	//向后台请求渠道信息
	//所有数据，和上一层id
	var childer2=[];  
	var childer=[];  
	function xxx(object,className){
		var type="";
		var name="";
		var flag="";
		if(className=="#treeTable1")
		{
			type="checkbox";
			name="sourceCheck";
			flag="name";
		}
		else
		{
			type="radio";
			name="safePort";
			flag="portName";
		}
		var a=[];
		var flag=0;
			var html="";
		var flaga={};
		
		function treeMenu(a){
		    this.tree=a||[];
		    this.groups={};
		};
		treeMenu.prototype={
		    init:function(superId){
		  
		        this.group();
		        return this.getDom(this.groups[superId]);
		    },
		    group:function(){
		    
		        for(var i=0;i<this.tree.length;i++){
		            if(this.groups[this.tree[i].superId]){
		                this.groups[this.tree[i].superId].push(this.tree[i]);
		            }else{
		                this.groups[this.tree[i].superId]=[];
		                this.groups[this.tree[i].superId].push(this.tree[i]);
		            }
		        }

		    },

		    getDom:function(a){
		    	
		    	
		        if(!a){return ''}
		       flag=0;
		        var html="";
		    
		    	if(a[0].superId==0)
		    	{
		    			/*$scope.sorce=a;//第一层结构
		    			//console.log($scope.sorce);*/
		    			for(var i=0;i<a.length;i++)
		    			{
		    				
		    				if(className=="#treeTable2")
		    				{
		    					html='<tr isChange=false id="'+a[i].id+'"   hasChild="hasChild" data-superid="'+a[i].superId+'" style="color:black;" ><td class="bianhao">'+(i+1)+'</td><td>'+a[i].name+'</td><td><input data-name='+a[i].portName+' data-id='+a[i].id+' type='+type+' name='+name+'></td></tr>\n';		
		    				}
		    				else
		    				{
		    					html='<tr isChange=false id="'+a[i].id+'"   hasChild="hasChild" data-superid="'+a[i].superId+'" style="color:black;" ><td class="bianhao">'+(i+1)+'</td><td>'+a[i].name+'</td><td><input data-name='+a[i].name+' data-id='+a[i].id+' type='+type+' name='+name+'></td></tr>\n';		

		    				}
		    				$(className).append(html);
		    				
		    			}
		    			
		    			flag=1;
		    	}
		    	////console.log("aa"+JSON.stringify(a));
		    	if(flag==0)
		    	{
		    			var length=a.length;
		    			var superid=0;
		    			for(var i=0;i<length;i++)
		    			{	
		    				superid=a[i].superId;
		    				if(isChilde(a[i].id,object))
		    				{ 
		    					
		    					if(className=="#treeTable2")
		    					{

		    					html+='<tr isChange=false id="'+a[i].id+'" hasChild="hasChild" pId="'+a[i].superId+'"   data-superid="'+a[i].superId+'" style="color:black;" ><td class="bianhao">'+(i+1)+'</td><td>'+a[i].name+'</td><td><input data-name='+a[i].portName+' data-id='+a[i].id+' type='+type+' name='+name+'></td> </tr>\n';		
		    					}
		    					else
		    					{
		    						html+='<tr isChange=false id="'+a[i].id+'" hasChild="hasChild" pId="'+a[i].superId+'"   data-superid="'+a[i].superId+'" style="color:black;" ><td class="bianhao">'+(i+1)+'</td><td>'+a[i].name+'</td><td><input data-name='+a[i].name+' data-id='+a[i].id+' type='+type+' name='+name+'></td> </tr>\n';		
		    					}

		    				}  
		    				else
		    				{  			
		    					if(className=="#treeTable2")
		    					{
		    							html+='<tr isChange=false id="'+a[i].id+'" pId="'+a[i].superId+'"   data-superid="'+a[i].superId+'" style="color:black;" ><td class="bianhao">'+(i+1)+'</td><td>'+a[i].portName+'</td><td><input data-name='+a[i].name+' data-id='+a[i].id+' type='+type+' name='+name+'></td></tr>\n';		
		    				
		    					}
		    					else
		    					{
		    						html+='<tr isChange=false id="'+a[i].id+'" pId="'+a[i].superId+'"   data-superid="'+a[i].superId+'" style="color:black;" ><td class="bianhao">'+(i+1)+'</td><td>'+a[i].name+'</td><td><input data-name='+a[i].name+' data-id='+a[i].id+' type='+type+' name='+name+'></td></tr>\n';		
		    				
		    					}
		    				}
		    				
		    				
		    				    
		    			}
		    				if(className=="#treeTable1")
		    				{
		    					childer.push({superid:superid,html:html});
		    				}
		    				else
		    				{
		    					childer2.push({superid:superid,html:html});
		    				}

		    			
		    		
		    		
		    			
		    	}
		    	 
		        for(var i=0;i<a.length;i++)
		        {
		           this.getDom(this.groups[a[i].id]);

		        }
	        /*html+='</optgroup>\n';*/
	       /* $("#"+id).append(html);*/
	        return html;
	    }
	   

	}
 var html=new treeMenu(object).init(0);
option(className);
}
	



//判断是否有子节点
function isChilde(id,object)
{
	for(var i=0;i<object.length;i++)
	{
		if(object[i].superId==id)
		{
			return true;
		}
	}
	return false;
}
	function option(className)
	{			
			var option = {
	                theme:'vsStyle',
	              
	                beforeExpand : function($treeTable, id) {

	            	var html="";
	                    //判断id是否已经有了孩子节点，如果有了就不再加载，这样就可以起到缓存的作用
	                    if ($('.' + id, $treeTable).length) { return; }
	            
	                   var index=$(className).find("tr").eq(id).attr("id");
	                   if(className=="#treeTable2")
		    			{
		                   for(var i=0;i<childer2.length;i++)
		                   {
		                   	if(id==childer2[i].superid)
		                   	{
		                   		html=childer2[i].html;
		                   	}
		                   }
		                 }
		                 else
		                 {
		                 	 for(var i=0;i<childer.length;i++)
		                   	{
		                   		if(id==childer[i].superid)
		                   		{
		                   			html=childer[i].html;
		                   		}
		                  	 }
		                 }
	                
	                     $treeTable.addChilds(html);
					},
					 onSelect : function($treeTable, id) {
	                    window.console && console.log('onSelect:' + id);
	                    
	                }


		}	
	
		$(className).treeTable(option);
	}


var x=1;	//向后台请求渠道信息
function space(superid,object)
{

	if(superid==0)
	{

		return 0;
	}
	for(var i=0;i<object.length;i++)
	{
		if(object[i].id==superid)
		{
			
			x=space(object[i].superId,object);
			
		}
	}
	return x+1;

}


function requestSource()
{	


	var url="getAllInfomationSource.do";//渠道地址
	var data={};
	var object={};
	var superId1=[];//第一层id
	YuXi.util.get(url,"null",function(data){
		object=data.object;
		
	xxx(object,"#treeTable1");
	
		
	},function(){});//请求数据



}	

//正则取链接传来的数据
function queryString(key)
{
    var regex_str = "^.+\\?.*?\\b"+ key +"=(.*?)(?:(?=&)|$|#)"
    var regex = new RegExp(regex_str,"i");
    var url = window.location.toString();
    if(regex.test(url)) return RegExp.$1;
    return undefined;
}






//根据id向后台请求数据详情
function requestDetail(id)
{	
	var url="getUserInformationById.do";//向后台请求数据id
	var object={}
	var sourceName;
	var personId;
	var personName;
	var dataid={informationId:id};
	YuXi.util.post(url,dataid,function(data){
		object=data.object;
		sourceName=object.informationSourceNames.split(",");
		personName=object.inputPerSonNames.split(",");
		personId=object.inputPersonID.split(",");
		setTimeout(function(){
			$("input[name='source']").each(function(){
				for(var i=0;i<sourceName.length;i++){
					if($(this).attr("data-na")==sourceName[i]){
						$(this).attr("checked","checked");
						break;
					}
				}
				
			});
		},100);
		for(var i=0;i<sourceName.length;i++){
			var html= "<label class='checkbox-inline'><input disabled type='checkbox' checked='checked' class='check'  name='source'>"+sourceName[i]+"</label>";
			$("#source").append(html);
		}
		addSelect(".sele",object.safetyPortNames);
		addSelect(".pes",object.informationClassificationNames);
		addSelect(".sort",object.informationSortNames);
		for(var i=0;i<personName.length;i++){
			if(personName[i]!=""){
				if(i<2){
					var html="<span class='parsbox'><span  class='glyphicon glyphicon-user' aria-hidden='true' ></span><span class='select-data-user personName' data-id="+personId[i]+">"+personName[i]+"</span></span>"
			        $(".joinPerson").append(html);
				}else
				{
					html="<span style='display:none' class='parsbox'><span  class='glyphicon glyphicon-user' aria-hidden='true' ></span><span class='select-data-user personName' data-id="+personId[i]+">"+personName[i]+"</span>&nbsp;&nbsp;<span   class='glyphicon glyphicon-remove' aria-hidden='true'></span></span>"
			        $(".joinPerson").append(html);
					
				}
				 if(i==2){
					html="  ...";
					$(".joinPerson").append(html);
				 }
				
			}
			
		}
		$(".briefing").html(object.informationProfile);//简介
		$(".basic").text(object.standard);//标准
		$(".step").text(object.mesure);//措施
		$(".cont").html(object.informationConternt);//内容
		
		file=object.appendix;
		if(file==null||file=="[]"){
			
		}else{
			file=JSON.parse(file);
			var appendix=object.appendix.substring(1,object.appendix.length-1);
			appendix=appendix.split(",");
			YuXi.appendix.get(appendix);
		}
	},function(){

	})

}



var fff={sele:false,sort:false,pes:false};
function addSelect(className,value){
	var length=className.length;
	
	var newname=className.substring(1,length);
	var time=setInterval(function(){
		if(fff.sele==true && fff.sort==true && fff.pes==true)
		{

			clearInterval(time);
		}
		if(checkFlag[newname]==true)
		{
			$(className+" option").each(function(){
			if($(this).html()==value){
				$(this).attr("selected","selected");

				if(className==".sele")
				{
					$(".select2-selection__rendered").eq(0).attr("title",value);
					$(".select2-selection__rendered").eq(0).html(value);
				}
				else if(className==".pes")
				{
					$(".select2-selection__rendered").eq(1).attr("title",value);
					$(".select2-selection__rendered").eq(1).html(value);
				}
				else
				{
					$(".select2-selection__rendered").eq(2).attr("title",value);
					$(".select2-selection__rendered").eq(2).html(value);
				}
				fff[newname]=true;
			}
			});
		}
		
	},50);
	
}	

function getInformation(){
	var information={};
	
    var personId=[];
    var personName=[];
    var check=[];
    var sourceName=[];
  
    $(".persoName").each(function(){
    	personId.push($(this).attr("data-id"));
		personName.push($(this).html());
		
		
	})
	information.id=detailId;
			var sourceid="";
	var sourcename="";
	 $('input:checkbox[name=sourceCheck]:checked').each(function(i){
	 		sourceid=sourceid+$(this).attr("data-id")+",";
	 		sourcename=sourcename+$(this).attr("data-name")+",";
	 })
	
    information.informationSourceID=sourceid;//渠道
    information.informationSourceNames=sourcename;

    information.informationClassificationId=parseInt($(".pes option:selected").val());//分级
    information.informationClassificationNames=($(".pes option:selected").html());
    information.informationSortId=($(".sort option:selected").val());//分类
    information.informationSortNames=($(".sort option:selected").html());
    information.mesure=$(".step").text();//措施
    information.standard=$(".basic").text();//标准
    information.informationProfile=$(".briefing").text();//简介
    information.informationConternt=$(".cont").text();//内容
    information.inputPersonID=personId.join(",");//参与人
    information.inputPerSonNames=personName.join(",");
    
    information.appendix=JSON.stringify(file);
    var overTime;
    var timeStr=$("input[id='overTime']").attr('placeholder');
    if($("#overTime").val()==null||$("#overTime").val()==""||$("#overTime").val()==timeStr){
    	 overTime="2080-12-31";
    }else{
    	 overTime=$("#overTime").val();
    }
    
	var time=new Date(Date.parse(overTime.replace(/-/g, "/")));
	var idStr="";
	var nameStr="";
	var span=$(".taskPeople").children("span");
	for(var i=0;i<span.length;i++){
		var name=span.eq(i).children("span").eq(1).html();
		var id=span.eq(i).children("span").eq(1).attr("data-id")
		idStr=id+","+idStr;
		nameStr=name+","+nameStr;
	}
	var note=$("#note").val();
    
	if(span.length==0){
		myTool.alert({
			title:"提示",
			context:"请选择责任人"
		});
		return false;
	}
	
    myTool.alert({		
		title:"提示",
		context:"是否确认对信息进行任务派遣?",
		isMask:true,
		callback:function(){
			requestUpdate(information,time,note,idStr,nameStr);
		}
	});
    
}
//确认过后返回
function goBack(){
	window.location.href="taskDispatchList.jsp?menuId=13";
}

//
function finishInfo(){
	var remark = $(".remark").val();
	YuXi.util.get("subToInfoFinsh.do",{infoId:detailId,remark:remark},function(data){
		 myTool.alert({
			 title:data.subType,
			 context:data.msg,
			 isMask:false,
				callback:function(){
					goBack();
				}
		 });
//		 
	 });
}

 

/*判断输入合法性*/
function isNull(str){
	if(str==null||str==""){
		return false;
	}else{
		return true;
	}
}


function modal(msg,cont){
	myTool.alert({		
		title:msg,
		context:cont,
		isMask:true,
		callback:function(){}
	});
}

//修改分口，分类，分级，标准，措施
function requestUpdate(information,time,note,idStr,nameStr)
{	var  flowName="";
	
	if(flowId==1){
		flowName="InfoManage";
	}
	if(flowId==2){
		flowName="FirstCheck";
	}
	if(flowId==3){
		flowName="ReCheck";
	}
	if(flowId==4){
		flowName="Check";
	}
	if(flowId==5){
		flowName="InfoResearch";
	}
	if(flowId==6){
		flowName="TaskDispatch";
	}
	if(flowId==7){
		flowName="CurTaskDispatch";
	}
	var url=flowName+"/userUpdataInformation.do";//修改的地址;
	YuXi.util.post(url,information,function(data){
		if(data.status)
		{ 	
			taskDispatch(time,note,idStr,nameStr);
		}else{
			myTool.alert({		
				title:"提示",
				context:"发生未知错误 ！",
				isMask:false,
				
			});
		}
	},function(){
//		myTool.alert({		
//			title:"提示",
//			context:"发生未知错误！",
//			isMask:true,
//			callback:function(){}
//		});
	})
}
	function taskDispatch(time,note,idStr,nameStr){
		var url="TaskDispatchFilter/taskDispatchModi.do";
		
		var args={informationId:detailId,overTime:time.getTime(),remark:note,personLiableId:idStr,perSonLiableName:nameStr};
		YuXi.util.get(url,args,function(data){
			if(data.status){
				myTool.alert({		
					title:"提示",
					context:"任务派遣成功",
					isMask:true,
					
				});
				setTimeout(function(){
					goBack();
				},1000);
			}
			else{
				myTool.alert({		
					title:"提示",
					context:"发生未知错误",
					isMask:true,
					callback:function(){}
				});
			}
		})
	}
//参与人选中后的确定按钮
function surePart()
{
	
	 var item=$(".ui-sortable .item");
     $("#node").find(".label1").html("");
     var pearson="";
     for(var i=0;i<item.length;i++)
     {
       firt=item[i].firstChild;
       if(i==item.length-1)
       {
         pearson+=firt.nextSibling.nodeValue;
       }
       else
       {
         pearson+=firt.nextSibling.nodeValue+",";

       }
       html="<span class='parsbox'><span  class='glyphicon glyphicon-user' aria-hidden='true'></span>"+firt.nextSibling.nodeValue+"&nbsp;&nbsp;</span></span>"
       $(".label1").append(html);
     }
     $('#myPart').modal('hide');
	
}
})